package com.alibaba.springbootrbac.service.impl;

import com.alibaba.springbootrbac.mapper.PermissionMapper;
import com.alibaba.springbootrbac.mapper.RoleMapper;
import com.alibaba.springbootrbac.mapper.RolePermissionMapper;
import com.alibaba.springbootrbac.model.entity.Role;
import com.alibaba.springbootrbac.model.param.role.*;
import com.alibaba.springbootrbac.service.RoleService;
import com.alibaba.springbootrbac.utils.BizException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author ZhouYaDong
 * @date 2025/8/22
 * @description
 */

@Service
@Transactional(rollbackFor = Exception.class) // 表示出现任何异常都会回滚
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private PermissionMapper permissionMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public void addRole(RoleParam param) {

        // 检查角色名称是否已经存在
        Role existingRole = roleMapper.selectOne(new QueryWrapper<Role>().eq("name", param.getName()));
        if (existingRole != null) {
            throw new BizException("角色名称已存在");
        }

        // 检查角色描述是否已经存在
        existingRole = roleMapper.selectOne(new QueryWrapper<Role>().eq("description", param.getDescription()));
        if (existingRole != null) {
            throw new BizException("角色描述已存在");
        }

        // 创建新角色并插入
        Role role = new Role();
        role.setName(param.getName());
        role.setDescription(param.getDescription());

        int insert = roleMapper.insert(role);
        if (insert == 0) {
            throw new BizException("role 新增失败");
        }
    }

    @Override
    public void updateRoleById(UpdateRoleParam param) {

        if (param.getId() == null){
            throw new BizException("更新失败，ID字段为空");
        }

        Role role = roleMapper.selectById(param.getId());
        // 更新之前先查询数据，为后面乐观锁提供版本号
        if (role == null) {
            throw new BizException("更新失败，ID=" + param.getId() + "，未找到该用户");
        }

        // 将param转成role
        role.setName(param.getName());
        role.setDescription(param.getDescription());

        //  版本号会自动参与乐观锁检查，MyBatis-Plus会自动处理
        int i = roleMapper.updateById(role);

        if (i == 0) {
            throw new BizException("role 更新失败");
        }

    }

    @Override
    public void deleteRoleById(DeleteRoleParam param) {
        int i = roleMapper.deleteById(param.getId());
        if (i == 0) {
            throw new BizException("用户信息删除失败，ID：" + param.getId());
        }
    }

    @Override
    public IPage<Role> queryRolesByPage(RolePageQueryParam param) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();

        // 动态查询条件
        // 查询条件：name 字段包含 param.getName() 的值（模糊匹配）
        if (param.getName() != null && !param.getName().isEmpty()) {
            queryWrapper.like("name", param.getName());
        }

        // 查询条件：description 字段包含 param.getDescription() 的值（模糊匹配）
        if (param.getDescription() != null && !param.getDescription().isEmpty()) {
            queryWrapper.like("description", param.getDescription());
        }

        // 创建时间大于或等于指定时间，查询 startCreateTime 之后或等于此时间的记录
        if (param.getStartCreateTime() != null) {
            queryWrapper.ge("create_time", param.getStartCreateTime());
        }

        // 创建时间小于或等于指定时间，查询 endCreateTime 之前或等于此时间的记录
        if (param.getEndCreateTime() != null) {
            queryWrapper.le("create_time", param.getEndCreateTime());
        }

        // 更新时间大于或等于指定时间，查询 startUpdateTime 之后或等于此时间的记录
        if (param.getStartUpdateTime() != null) {
            queryWrapper.ge("update_time", param.getStartUpdateTime());
        }

        // 更新时间小于或等于指定时间，查询 endUpdateTime 之前或等于此时间的记录
        if (param.getEndUpdateTime() != null) {
            queryWrapper.le("update_time", param.getEndUpdateTime());
        }

        // 分页参数处理，确保默认值
        int pageNum = param.getPageNum() != null ? param.getPageNum() : 1;  // 当前页，默认为1
        int pageSize = param.getPageSize() != null ? param.getPageSize() : 10;  // 每页条数，默认为10

        // 分页查询
        Page<Role> page = new Page<>(pageNum, pageSize);
        return roleMapper.selectPage(page, queryWrapper);
    }

    @Override
    public void assignPermissionsToRole(RolePermissionParam param) {
        // 删除角色已有的权限
        rolePermissionMapper.deleteByRoleId(param.getRoleId());

        // 为角色分配新的权限
        int i = rolePermissionMapper.insertRolePermissions(param.getRoleId(), param.getPermissionIds());

        if (i == 0) {
            throw new BizException("为角色分配权限失败");
        }
    }

    @Override
    public void removePermissionFromRole(RolePermissionParam param) {
        // 获取权限ID
        String permissionId = param.getPermissionIds().get(0); // 假设只删除一个权限
        // 删除角色的权限
        int i = rolePermissionMapper.deleteByRoleIdAndPermissionId(param.getRoleId(), permissionId);
        if (i == 0) {
            throw new BizException("删除角色的权限失败");
        }
    }

    @Override
    public void removePermissionsFromRole(RolePermissionParam param) {
        int i = rolePermissionMapper.deleteRolePermissionsBatch(param.getRoleId(), param.getPermissionIds());
        if (i == 0) {
            throw new BizException("批量删除角色的权限失败");
        }
    }
}
